package org.example.monitor;

import org.example.ThreadPoolManager;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;


/**
 * 监控服务类
 */
public class MonitoringService {
    private final List<Monitorable> monitorableComponents = new CopyOnWriteArrayList<>();
    private final AtomicBoolean running = new AtomicBoolean(false);
    private final long monitorInterval;
    private final TimeUnit timeUnit;

    private ScheduledFuture<?> monitoringTask;

    public MonitoringService(long monitorInterval, TimeUnit timeUnit) {
        this.monitorInterval = monitorInterval;
        this.timeUnit = timeUnit;
    }

    public void registerComponent(Monitorable component) {
        monitorableComponents.add(component);
        System.out.println("Registered monitoring component: " + component.getComponentName());
    }

    public void start() {
        if (running.compareAndSet(false, true)) {
            // 使用统一的线程池，而不是自己创建
            ScheduledExecutorService scheduler = ThreadPoolManager.getInstance().getScheduledExecutor();

            monitoringTask = scheduler.scheduleAtFixedRate(
                    this::monitorAllComponents,
                    1, // 初始延迟
                    monitorInterval,
                    timeUnit
            );
            System.out.println("MonitoringService started with interval: " + monitorInterval + " " + timeUnit);
        }
    }

    public void stop() {
        if (running.compareAndSet(true, false) && monitoringTask != null) {
            monitoringTask.cancel(false);
            System.out.println("MonitoringService stopped");
        }
    }

    private void monitorAllComponents() {
        for (Monitorable component : monitorableComponents) {
            try {
                component.executeMonitorCycle();
            } catch (Exception e) {
                System.err.println("Error monitoring " + component.getComponentName() + ": " + e.getMessage());
            }
        }
    }
}